package layui.controller;

import com.google.gson.GsonBuilder;
import layui.vo.PageVo;
import layui.vo.ResponseData;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *  所有Servlet 的父类 -把所有相同的代码提取到父类中，实现共享
 *
 * @Author lzp
 * @Date 2023-11-22
 */
public abstract class BaseServlet extends HttpServlet {
    /**
     * 成功响应的数据封装 - 默认
     *
     * @param data
     * @return
     */
    public ResponseData successJson(Object data) {
        return new ResponseData(200, "success", data);
    }

    /**
     * 重载成功响应数据封装方法
     *
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public ResponseData successJson(Integer code, String msg, Object data) {
        return new ResponseData(code, msg, data);
    }

    /**
     * 失败响应的数据封装 - 默认
     *
     * @return
     */
    public ResponseData errorJson() {
        return new ResponseData(500, "error", null);
    }

    /**
     * 重载成功响应数据封装方法
     *
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public ResponseData errorJson(Integer code, String msg, Object data) {
        return new ResponseData(code, msg, data);
    }


    public  void print(HttpServletResponse resp, ResponseData responseData)  throws IOException {
        //设置编码
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        // out.println(new Gson().toJson(responseData));
        out.println(new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss")
                .create()
                .toJson(responseData));
        out.flush();
        out.close();
    }

    public PageVo pageVo(Long count,Object data) {
        return new PageVo(0,"success",data,count) ;
    }

}
